package com.itbaizhan.springsecuritydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itbaizhan.springsecuritydemo.domain.Permission;
import com.itbaizhan.springsecuritydemo.domain.Users;
import com.itbaizhan.springsecuritydemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//只可以有一个认证类，所以将config包下的userDetailsManager()方法注释
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

//自定义认证逻辑
    /*提交表单，得到要查询的用户（不获取密码），与数据库的用户作对比，如果查到用户，则封装
    * 为userDetails对象（把从数据库里得到的用户名与密码封装），最后security会将userDetail对象中的密码与表单的密码比较*/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1,构造查询条件
        QueryWrapper<Users> query = new QueryWrapper<Users>().eq("username",username);
        //2,查询用户
        Users users = userMapper.selectOne(query);
        if(users == null){
            return null;
        }
        //3查询用户权限
        List<Permission> permissions = userMapper.findpermissionByUsername(username);
        //GrantedAuthority集合类型的对象是spring security的自带对象，要将自定义的权限集合转换为GrantedAuthority
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for(Permission permission : permissions){
            //SimpleGrantedAuthority 简单的接口，把权限路径放进去，这路径代表权限路径，资源路径
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        }
        //4封装为UserDetails对象
        UserDetails userDetails = User.withUsername(users.getUsername())
                .password(users.getPassword())
                .authorities(grantedAuthorities)  //传入一个GrantedAuthority对象的集合
                .build();
        //返回封装好的UserDetails对象
        return userDetails;
    }
}
